<?php
// +----------------------------------------------------------------------
// | TYCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: aliang <461321026@qq.com>
// +----------------------------------------------------------------------
namespace app\home\controller;

use think\Cache;
use think\Db;
use think\captcha\Captcha;

class Index extends Base
{
	public function index()
    { 
       
        $goods_size = 12;        
        $uid        = session('hid') ? session('hid'):0;
        $member_group_id = 0;
        if($uid >0){
           $member  = db("member_list")->where("member_list_id",$uid)->find();
           $member_group_id = isset($member['member_list_groupid']) ? $member['member_list_groupid']:0;
        }
        
        $cache_name = "index_goods_list_{$member_group_id}_{$goods_size}";
        $goods_list  = cache($cache_name);
        if(empty($goods_list)){
            $where = " FIND_IN_SET('t',g.goods_flag) ";
            $maps  = ["g.status"=>1];
            $goods_list = Db::name('goods')->alias("g")->join("__GOODS_CATE__ gc","gc.gid = g.id","LEFT")
                          ->join("__GOODS_PRICE__ gp","gp.gid = g.id","LEFT")
                          ->where($maps)
                          ->where($where)->field("g.id,g.goods_title,g.thumb,g.price,gc.cid,gp.price_1,gp.price_2,gp.price_3")->limit($goods_size)->order('listorder asc,id desc')->select();
            foreach($goods_list as $k=>$v){
                if($member_group_id == 0)
                    $goods_list[$k]['true_price'] = $v['price'];
                else{
                    $keys = 'price_'.$member_group_id;
                    $goods_list[$k]['true_price'] = isset($v[$keys]) ? $v[$keys]:$v['price'];
                }
            }
            cache($cache_name,$goods_list);    
        }
        $this->assign("goods_list",$goods_list);
		return $this->view->fetch(':index');
	}
	
	
	public function visit()
    {
		$user=Db::name("member_list")->where(array("member_list_id"=>input('id',0,'intval')))->find();
		if(empty($user)){
			$this->error(lang('member not exist'));
		}
		$this->assign($user);
		return $this->view->fetch('user:index');
	}
	public function verify_msg()
	{
		//ob_end_clean();
		$verify = new Captcha (config('verify'));
		return $verify->entry('msg');
	}
	public function lang()
	{
		if (!request()->isAjax()){
			$this->error(lang('submission mode incorrect'));
		}else{
			$lang=input('lang_s');
			switch ($lang) {
				case 'cn':
					cookie('think_var', 'zh-cn');
				break;
				case 'en':
					cookie('think_var', 'en-us');
				break;
				//其它语言
				default:
					cookie('think_var', 'zh-cn');
			}
			Cache::clear();
			$this->success(lang('success'),url('home/Index/index'));
		}
	}
	
   public function feedback(){
       if(request()->isPost()){
           $data=array(
               'plug_sug_name'=>'',
               'plug_sug_mobile'=>'',
               'plug_sug_email'=>'',
               'plug_sug_content'=>input('content','','strip_tags,htmlspecialchars'),
               'plug_sug_addtime'=>time(),
               'plug_sug_open'=>0,
               'plug_sug_ip'=>request()->ip(),
           );
           $name = input('name','','strip_tags,htmlspecialchars');
           if(empty($name) || empty($data['plug_sug_content'])){
               $this->error('联系方式或反馈内容不能为空！');
           }
           if(isMobile($name)){
              $data['plug_sug_mobile']  = $name;
           }elseif(isMail($name)){
              $data['plug_sug_email']   = $name;
           }else{ 
              $data['plug_sug_name']    = $name;
           }
  
           $rst=Db::name('plug_sug')->insert($data);
           if($rst!==false){
               $this->success('提交成功！');
           }else{
               $this->error(lang('message failed'));
           }
           
       }
       return $this->view->fetch(':feedback');
   }
	
	
	public function addmsg()
    {
	   if(request()->isPost()){
			$data=array(
				'plug_sug_name'=>input('plug_sug_name'),
			    'plug_sug_mobile'=>input('plug_sug_mobile'),
			    'plug_sug_email'=>input('plug_sug_email'),
				'plug_sug_content'=>input('plug_sug_content'),
				'plug_sug_addtime'=>time(),
				'plug_sug_open'=>0,
				'plug_sug_ip'=>request()->ip(),
			);
			
			if(!isMobile($data['plug_sug_mobile'])){
			    $this->error('手机号码格式错误！');
			}
			
			if(empty($data['plug_sug_name']))
			    $this->error('姓名不能为空！');
			
			if(!isMail($data['plug_sug_email'])){
			    $this->error('邮箱格式错误！');
			}
			 
			
			$verify =new Captcha ();
			if (!$verify->check(input('verify'), 'msg')) {
				$this->error(lang('verifiy incorrect'));
			}
	    
			$data['plug_sug_content'] = empty($data['plug_sug_content'])  ? '首页提交领取':$data['plug_sug_content'];
			$rst=Db::name('plug_sug')->insert($data);
			if($rst!==false){
				$this->success('提交成功！');
			}else{
				$this->error(lang('message failed'));
			}
		    }else{
		        $end_time = cookie('st_end_time') ? cookie('st_end_time'):(time()+7*3600);
		        cookie('st_end_time',$end_time);
		        $this->assign('end_time',$end_time);
		        
		        return $this->view->fetch(':addmsg');
		    }
		 
	}
	
	public function check_forget(){
	    $param = input('post.');
	    if(empty($param["mobile"]) || empty($param['code'])){
	        return json(["err"=>1,"msg"=>"缺少参数！"]);
	    }
	    $info = Db::name("member_send_msg")->where("val",$param["mobile"])->find();
	    if(empty($info))
	        return json(["err"=>1,"msg"=>"该手机号没有绑定！"]);
	    
	    if($info['code'] == $param['code'] && $info['uid']>0){
	        return json(["err"=>0,"msg"=>"验证通过！"]);
	    }else{
	        return json(["err"=>1,"msg"=>"验证信息不正确！"]);
	    }
	}

    
    //手机验证码
    public function mobilecode(){
        $param = input();
        if(empty($param["mobile"])){
            return json(["err"=>1,"msg"=>"缺少参数！"]);
        }
        $errnum = session('errnum_'.$param["mobile"]);
        $errnum = intval($errnum);
        if($errnum>=10){
            return json(["err"=>1,"msg"=>"抱歉，该手机号发送的短信超出限制！"]);
        }
        $rand = random(5,'number');
        /*
        $data = [
            'address' => $param["mobile"],
            'title'   => '手机验证码',
            'content' => '验证码:('.$rand.')'
        ];
        */
        $mode = input('mode') ? input('mode'):'';
        $info = Db::name("member_send_msg")->where("val",$param["mobile"])->find();
        if($mode == 'forget'){
           $isbind = isset($info['isbind']) && $info['isbind']==1;
           if(empty($info) || !$isbind){
              return json(["err"=>1,"msg"=>"该手机号没有绑定！"]); 
           } 
        }else{
           if(!empty($info) && $info['isbind'] == 1){
            return json(["err"=>1,"msg"=>"该手机号已经被注册，不能重复注册！"]);
           }
        }
        
        $ParamString = '{"no":"'.$rand.'"}';  //后台需设置模版例如：      验证码:${no}
        $sms_sys     = sys_config_get('think_sdk_sms');
        //$notice = new \org\Tips($sms_sys);
        //$result = $notice->send($data,'mobile'); 
        $sms = new \Alisms($sms_sys);
        $result = $sms->smsend($param["mobile"],$ParamString);
         
        //$result["Code"] = 'OK';
        if($result->Code == 'OK'){
            if($info){
                //更新
                $info["code"] = $rand;
                $info["add_time"]   = time();
                $info["expire_time"]= time()+3600;
                $info["isbind"]     = $info['isbind'];
                $info["ip"] = request()->ip();
                $res = Db::name("member_send_msg")->update($info);
            }else{
                //新增
                $msg = [
                    "uid"=> 0,
                    "val"=> $param["mobile"],
                    "code"=> $rand,
                    "add_time"=> time(),
                    "expire_time"=> time()+3600,
                    "isbind"=> 0,
                    "ip"=> request()->ip(),
                ];
                $res = Db::name("member_send_msg")->insert($msg);
            }
            if($res){
                $errnum++;
                session('errnum_'.$param["mobile"],$errnum);
                return json(["err"=>0,"msg"=>"发送成功！","data"=>$rand]);//
            }else{
                return json(["err"=>1,"msg"=>"服务器出错，可能无法相关操作，请联系管理员！"]);
            }
        }else{
            return json(["err"=>1,"msg"=>"验证码发送失败！错误信息:".$result->Message]);
        }
    }
}